﻿import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import QtQuick.Dialogs
import QtCore
import QtQml
import FilUI

import "../controls"
import SecAssistPro

Item {
    id: control

    property StackView parentStackView
    property string modifyPid: ""

    signal clickBack()

    property alias pname                        : id_filtextbox__pname.text
    property alias wdir                         : id_filtextbox__wdir.text
    property alias dspath                       : id_filtextbox__dspath.text
    property alias dspath_enable                : id_filcheckbox__dspath.checked
    property alias uspath                       : id_filtextbox__uspath.text
    property alias uspath_enable                : id_filcheckbox__uspath.checked
    property alias enable_fsw                   : id_filcheckbox__fsw.checked
    property string title: qsTr("Modify Project")
    property int rightScrollableMargin: 18
    property int footerHeight: 8
    property int frameSpacing: 12

    onClickBack: {
        parentStackView.popCurrentItem()
    }

    ColumnLayout {
        id: id_columnlayout
        anchors.fill                            : parent
        Item {
            Layout.preferredHeight              : 35
            Layout.preferredWidth               : parent.width
            RowLayout {
                anchors.fill                    : parent
                spacing                         : 5
                FilIconButton {
                    Layout.leftMargin           : 10
                    iconSize                    : 20
                    color                       : Qt.rgba(0, 0, 0, 0)
                    iconColor                   : {
                        if (!enabled) {
                            return Qt.rgba(161/255, 161/255, 161/255, 1)
                        }
                        if (pressed) {
                            return Qt.rgba(0, 0, 0, 0.6)
                        }
                        return hovered ? Qt.rgba(0, 0, 0, 0.3) : Qt.rgba(0, 0, 0, 1)
                    }
                    iconSource                  : FilIcons.ChromeBack
                    text                        : qsTr("Back")
                    onClicked                   : {
                        control.clickBack()
                    }
                }
                FilText {
                    text                        : control.title
                    font.pixelSize              : 22
                }
                FilText {
                    id: id_filtext__pid
                    text                        : "PID :"
                    font.pixelSize              : 12
                    color                       : "gray"
                    Layout.leftMargin           : 2
                    Layout.topMargin            : 9
                }
                FilCopyableText {
                    id: id_filcopyabletext__pid
                    text                        : control.modifyPid
                    font.pixelSize              : 12
                    color                       : "gray"
                    Layout.topMargin            : 9
                }
                Item {
                    // 填补中间空白
                    Layout.fillWidth            : true
                }
                FilButton {
                    Layout.preferredWidth       : 75
                    Layout.preferredHeight      : 32
                    text                        : qsTr("Cancel")
                    onClicked                   : {
                        id_filcontentdialog__back.open()
                    }
                }
                FilFilledButton {
                    Layout.preferredWidth       : 75
                    Layout.rightMargin          : 15
                    text                        : qsTr("Confirm")
                    onClicked                   : {
                        control.modifyProject()
                    }
                }
            }
        }
        FilScrollablePage {
            Layout.fillHeight                   : true
            Layout.preferredWidth               : parent.width
            leftPadding                         : 25
            rightPadding                        : 8
            /**********************************/
            /**********************************/
            /**********************************/
            /**********************************/
            FilFrame {
                id: id_filframe__pname
                Layout.fillWidth: true
                padding: 10
                color: "transparent"
                Layout.preferredHeight: 80
                Layout.rightMargin: control.rightScrollableMargin
                ColumnLayout {
                    anchors.fill: parent
                    spacing: 5
                    Row {
                        width: parent.width
                        spacing: 5
                        FilText {
                            text: qsTr("Project Name")
                            font: FilTextStyle.BodyStrong
                            Layout.bottomMargin: 4
                            Layout.preferredWidth: id_filframe__pname.width
                        }
                        // 工程名称提示信息，比如存在重复工程名称
                        FilText {
                            id: id_filtext__pnametips
                            text: qsTr("( The same project name already exists. )")
                            font: FilTextStyle.BodyStrong
                            Layout.bottomMargin: 4
                            color: "red"
                            Behavior on opacity {
                                NumberAnimation { duration: 300 }
                            }
                            state: "invisible"
                            states: [
                                State {
                                    name: "visible"
                                    PropertyChanges { id_filtext__pnametips.opacity: 1 }
                                },
                                State {
                                    name: "invisible"
                                    PropertyChanges { id_filtext__pnametips.opacity: 0 }
                                }
                            ]
                        }
                    }
                    FilTextBox {
                        id: id_filtextbox__pname
                        Layout.fillWidth: true
                        onTextChanged: {
                            // id_timer__pnameCheckExist.restart()
                        }
                        function checkPNameExist() {
                            if (text.length > 0) {
                                var pid = ProjectDbHelper.getPidByName(text)
                                id_filtext__pnametips.state = pid.length > 0 ? "visible" : "invisible"
                            } else {
                                id_filtext__pnametips.state = "invisible"
                            }
                        }
                    }
                    Timer {
                        id: id_timer__pnameCheckExist
                        interval: 500
                        onTriggered: {
                            id_filtextbox__pname.checkPNameExist()
                        }
                    }
                }
            }
            /**********************************/
            /**********************************/
            /**********************************/
            /**********************************/
            FilFrame {
                id: id_filframe__wdir
                Layout.fillWidth: true
                padding: 10
                color: "transparent"
                Layout.preferredHeight: 80
                Layout.rightMargin: control.rightScrollableMargin
                Layout.topMargin: control.frameSpacing
                Item {
                    id: id_item__wdir
                    anchors.fill: parent
                    ColumnLayout {
                        spacing: 5
                        anchors.fill: parent
                        Row {
                            width: parent.width
                            spacing: 10
                            FilText {
                                text: qsTr("Work Directory")
                                font: FilTextStyle.BodyStrong
                                Layout.bottomMargin: 4
                            }
                            FilText { // 路径合法性提示框
                                id: id_filtext__wdirtips
                                text: qsTr("( Invalid or non-existent path )")
                                font: FilTextStyle.BodyStrong
                                Layout.bottomMargin: 4
                                color: "red"
                                Behavior on opacity {
                                    NumberAnimation { duration: 300 }
                                }
                                state: "invisible"
                                states: [
                                    State {
                                        name: "visible"
                                        PropertyChanges { id_filtext__wdirtips.opacity: 1 }
                                    },
                                    State {
                                        name: "invisible"
                                        PropertyChanges { id_filtext__wdirtips.opacity: 0 }
                                    }

                                ]
                            }
                        }
                        RowLayout {
                            width: parent.width
                            spacing: 5
                            Layout.bottomMargin: 10
                            FilTextBox {
                                id: id_filtextbox__wdir
                                Layout.fillWidth: true
                                // 修正用户输入的Windows路径分隔符'\'
                                onTextEdited: {
                                    text = text.replace(/\\/g, "/")
                                }
                                onTextChanged: {
                                    id_timer__wdirCheckDirExist.restart()
                                }
                                function checkDirExist() {
                                    if (text.length > 0) {
                                        id_filtext__wdirtips.state = FilTools.checkDirExist(text) ? "invisible" : "visible"
                                    } else {
                                        id_filtext__wdirtips.state = "invisible"
                                    }
                                }
                            }
                            FilIconButton {
                                iconSource: FilIcons.FolderOpen
                                iconSize: 16
                                onClicked: {
                                    id_folderdialog__wdir.open()
                                }
                            }
                        }
                    }
                    FolderDialog {
                        id: id_folderdialog__wdir
                        title: qsTr("Open Folder")
                        currentFolder: {
                            if (FilTools.checkDirExist(control.wdir)) {
                                return FilTools.getUrlByFilePath(control.wdir)
                            }
                            return StandardPaths.standardLocations(StandardPaths.DocumentsLocation)[0]
                        }
                        onAccepted: {
                            // id_filtextbox__wdir.text = Qt.resolvedUrl(selectedFolder).toString().replace(/^(file:\/{3})/, "")
                            var text = FilTools.toLocalPath(selectedFolder).replace(/\\/g, "/")
                            id_filtextbox__wdir.text = text
                        }
                    }
                    Timer {
                        id: id_timer__wdirCheckDirExist
                        interval: 500
                        onTriggered: {
                            id_filtextbox__wdir.checkDirExist()
                        }
                    }
                }
            }
            /**********************************/
            /**********************************/
            /**********************************/
            /**********************************/
            FilFrame {
                id: id_filframe__dspath
                Layout.fillWidth: true
                padding: 10
                color: "transparent"
                Layout.preferredHeight: 110
                Layout.rightMargin: control.rightScrollableMargin
                Layout.topMargin: control.frameSpacing
                ColumnLayout {
                    anchors.fill: parent
                    spacing: 8
                    Row {
                        width: parent.width
                        spacing: 5
                        FilText {
                            text: qsTr("Download Script")
                            font: FilTextStyle.BodyStrong
                            Layout.bottomMargin: 4
                        }
                        FilText {
                            id: id_filtext__dspathtips
                            text: qsTr("( Invalid or non-existent path )")
                            font: FilTextStyle.BodyStrong
                            Layout.bottomMargin: 4
                            color: "red"
                            Behavior on opacity {
                                NumberAnimation { duration: 300 }
                            }
                            state: "invisible"
                            states: [
                                State {
                                    name: "visible"
                                    PropertyChanges { id_filtext__dspathtips.opacity: 1 }
                                },
                                State {
                                    name: "invisible"
                                    PropertyChanges { id_filtext__dspathtips.opacity: 0 }
                                }
                            ]
                        }
                    }
                    RowLayout {
                        width: parent.width
                        spacing: 5
                        FilTextBox {
                            id: id_filtextbox__dspath
                            Layout.fillWidth: true
                            // 修正用户输入的Windows路径分隔符'\'
                            onTextEdited: {
                                text = text.replace(/\\/g, "/")
                            }
                            onTextChanged: {
                                id_timer__dspathCheckDirExist.restart()
                            }
                            function checkDirExist() {
                                if (text.length > 0) {
                                    id_filtext__dspathtips.state = FilTools.checkFileExist(text) ? "invisible" : "visible"
                                } else {
                                    id_filtext__dspathtips.state = "invisible"
                                }
                            }
                        }
                        FilIconButton {
                            iconSource: FilIcons.OpenFile
                            iconSize: 16
                            onClicked: {
                                id_filedialog__dspath.open()
                            }
                        }
                    }
                    RowLayout {
                        width: parent.width
                        spacing: 5
                        FilCheckBox {
                            id: id_filcheckbox__dspath
                            text: qsTr("Enable")
                            Layout.alignment: Qt.AlignVCenter
                        }
                    }
                    FileDialog {
                        id: id_filedialog__dspath
                        title: qsTr("Open File")
                        fileMode: FileDialog.OpenFile
                        currentFolder: {
                            if (FilTools.checkDirExist(control.wdir)) {
                                return FilTools.getUrlByFilePath(control.wdir)
                            }
                            return StandardPaths.standardLocations(StandardPaths.DocumentsLocation)[0]
                        }
                        onAccepted: {
                            // id_filtextbox__dspath.text = Qt.resolvedUrl(selectedFile).toString().replace(/^(file:\/{3})/, "")
                            var text = FilTools.toLocalPath(selectedFile).replace(/\\/g, "/")
                            id_filtextbox__dspath.text = text
                        }
                    }
                    Timer {
                        id: id_timer__dspathCheckDirExist
                        interval: 500
                        onTriggered: {
                            id_filtextbox__dspath.checkDirExist()
                        }
                    }
                }
            }
            /**********************************/
            /**********************************/
            /**********************************/
            /**********************************/
            FilFrame {
                Layout.fillWidth: true
                padding: 10
                color: "transparent"
                Layout.preferredHeight: 110
                Layout.rightMargin: control.rightScrollableMargin
                Layout.topMargin: control.frameSpacing
                ColumnLayout {
                    anchors.fill: parent
                    spacing: 8
                    Row {
                        width: parent.width
                        spacing: 5
                        FilText {
                            text: qsTr("Upload Script")
                            font: FilTextStyle.BodyStrong
                            Layout.bottomMargin: 4
                        }
                        FilText {
                            id: id_filtext__uspathtips
                            text: qsTr("( Invalid or non-existent path )")
                            font: FilTextStyle.BodyStrong
                            Layout.bottomMargin: 4
                            color: "red"
                            Behavior on opacity {
                                NumberAnimation { duration: 300 }
                            }
                            state: "invisible"
                            states: [
                                State {
                                    name: "visible"
                                    PropertyChanges { id_filtext__uspathtips.opacity: 1 }
                                },
                                State {
                                    name: "invisible"
                                    PropertyChanges { id_filtext__uspathtips.opacity: 0 }
                                }
                            ]
                        }
                    }
                    RowLayout {
                        width: parent.width
                        spacing: 5
                        FilTextBox {
                            id: id_filtextbox__uspath
                            Layout.fillWidth: true
                            // 修正用户输入的Windows路径分隔符'\'
                            onTextEdited: {
                                text = text.replace(/\\/g, "/")
                            }
                            onTextChanged: {
                                id_timer__uspathCheckDirExist.restart()
                            }
                            function checkDirExist() {
                                if (text.length > 0) {
                                    id_filtext__uspathtips.state = FilTools.checkFileExist(text) ? "invisible" : "visible"
                                } else {
                                    id_filtext__uspathtips.state = "invisible"
                                }
                            }
                        }
                        FilIconButton {
                            iconSource: FilIcons.OpenFile
                            iconSize: 16
                            onClicked: {
                                id_filedialog__uspath.open()
                            }
                        }
                    }
                    RowLayout {
                        width: parent.width
                        spacing: 5
                        FilCheckBox {
                            id: id_filcheckbox__uspath
                            text: qsTr("Enable")
                            Layout.alignment: Qt.AlignVCenter
                        }
                    }
                    FileDialog {
                        id: id_filedialog__uspath
                        title: qsTr("Open File")
                        fileMode: FileDialog.OpenFile
                        currentFolder: {
                            if (FilTools.checkDirExist(control.wdir)) {
                                return FilTools.getUrlByFilePath(control.wdir)
                            }
                            return StandardPaths.standardLocations(StandardPaths.DocumentsLocation)[0]
                        }
                        onAccepted: {
                            // id_filtextbox__uspath.text = Qt.resolvedUrl(selectedFile).toString().replace(/^(file:\/{3})/, "")
                            var text = FilTools.toLocalPath(selectedFile).replace(/\\/g, "/")
                            id_filtextbox__uspath.text = text
                        }
                    }
                    Timer {
                        id: id_timer__uspathCheckDirExist
                        interval: 500
                        onTriggered: {
                            id_filtextbox__uspath.checkDirExist()
                        }
                    }
                }
            }
            /**********************************/
            /**********************************/
            /**********************************/
            /**********************************/
            FilFrame {
                Layout.fillWidth: true
                padding: 10
                color: "transparent"
                Layout.preferredHeight: 70
                Layout.rightMargin: control.rightScrollableMargin
                Layout.topMargin: control.frameSpacing
                ColumnLayout {
                    anchors.fill: parent
                    spacing: 5
                    Row {
                        width: parent.width
                        spacing: 5
                        FilText {
                            text: qsTr("File System Watcher")
                            font: FilTextStyle.BodyStrong
                            Layout.bottomMargin: 4
                        }
                    }
                    RowLayout {
                        width: parent.width
                        spacing: 5
                        FilCheckBox {
                            id: id_filcheckbox__fsw
                            text: qsTr("Enable")
                            Layout.alignment: Qt.AlignVCenter
                        }
                    }
                }
            }
            /**********************************/
            /**********************************/
            /**********************************/
            /**********************************/
            FilFrame {
                id: id_filframe__uploadfileconfig
                property var jsonfile
                Layout.fillWidth: true
                padding: 10
                color: "transparent"
                Layout.preferredHeight: 300
                Layout.rightMargin: control.rightScrollableMargin
                Layout.topMargin: control.frameSpacing
                ColumnLayout {
                    anchors.fill: parent
                    spacing: 5
                    Row {
                        width: parent.width
                        spacing: 5
                        FilText {
                            text: qsTr("Upload File Configuration")
                            font: FilTextStyle.BodyStrong
                            Layout.bottomMargin: 4
                            anchors.verticalCenter: parent.verticalCenter
                        }
                        FilIconButton {
                            text: qsTr("Add")
                            iconSource: FilIcons.Add
                            iconSize: 15
                            onClicked: {
                                // id_filcontentdialog__add.open()
                                id_filedialog__additem.open()
                            }
                            FileDialog {
                                id: id_filedialog__additem
                                title: qsTr("Open File")
                                fileMode: FileDialog.OpenFile
                                currentFolder: {
                                    if (FilTools.checkDirExist(control.wdir)) {
                                        return FilTools.getUrlByFilePath(control.wdir)
                                    }
                                    return StandardPaths.standardLocations(StandardPaths.DocumentsLocation)[0]
                                }
                                onAccepted: {
                                    var text = FilTools.toLocalPath(selectedFile).replace(/\\/g, "/")
                                    id_filtableview__ufc.appendRow({
                                        checkbox: id_filtableview__ufc.customItem(id_component__checkbox, {checked: false}),
                                        path: text,
                                        action: id_filtableview__ufc.customItem(id_component__action, {}),
                                        _key: FilTools.uuid()
                                    })
                                }
                            }
                        }
                        FilIconButton {
                            text: qsTr("Remove")
                            iconSource: FilIcons.Remove
                            iconSize: 15
                            onClicked: {
                                var currentIndex = id_filtableview__ufc.currentIndex()
                                console.log("Remove currentIndex:", currentIndex)
                                id_filtableview__ufc.removeRow(currentIndex)
                            }
                        }
                    }
                    RowLayout {
                        // 用于绑定表格列宽占比的模板，使表格可以根据整体窗口大小进行自适应调整
                        id: id_row__interval
                        spacing: 1
                        property var header: [id_rect__n, id_rect__c, id_rect__p, id_rect__b]
                        property int blockHeight: 0
                        Rectangle { // number delegate
                            id: id_rect__n
                            Layout.preferredWidth: 30
                            height: id_row__interval.blockHeight
                            color: "green"
                            visible: id_filtableview__ufc.rows > 1
                        }
                        Rectangle { // checkbox
                            id: id_rect__c
                            Layout.preferredWidth: 100
                            height: id_row__interval.blockHeight
                            color: "red"
                        }
                        Rectangle { // path
                            id: id_rect__p
                            Layout.fillWidth: true
                            height: id_row__interval.blockHeight
                            color: "blue"
                        }
                        Rectangle { // open file button
                            id: id_rect__b
                            Layout.preferredWidth: 80
                            height: id_row__interval.blockHeight
                            color: "green"
                        }
                    }
                    // list
                    Item {
                        id: id_item__ufc // uploadfileconfig
                        Layout.fillHeight: true
                        Layout.preferredWidth: parent.width
                        property bool selectedAll: true
                        signal checkBoxChanged()
                        onCheckBoxChanged: {
                            for (var i = 0; i < id_filtableview__ufc.rows; i++) {
                                if (id_filtableview__ufc.getRow(i).checkbox.options.checked === false) {
                                    id_item__ufc.selectedAll = false
                                    return
                                }
                            }
                        }
                        Component {
                            id: id_component__checkbox
                            Item {
                                FilCheckBox {
                                    anchors.centerIn: parent
                                    checked: true === options.checked
                                    animationEnabled: FilTheme.animationEnabled
                                    clickListener: function() {
                                        var obj = id_filtableview__ufc.getRow(row)
                                        obj.checkbox = id_filtableview__ufc.customItem(id_component__checkbox, {checked: !options.checked})
                                        id_filtableview__ufc.setRow(row, obj)
                                        id_item__ufc.checkBoxChanged()
                                    }
                                }
                            }
                        }
                        Component {
                            id: id_component__column_checkbox
                            Item {
                                RowLayout {
                                    anchors.centerIn: parent
                                    FilText {
                                        text: qsTr("Enable")
                                        Layout.alignment: Qt.AlignVCenter
                                    }
                                    FilCheckBox {
                                        checked: true === id_item__ufc.selectedAll
                                        animationEnabled: FilTheme.animationEnabled
                                        Layout.alignment: Qt.AlignVCenter
                                        clickListener: function() {
                                            id_item__ufc.selectedAll = !id_item__ufc.selectedAll
                                            var checked = id_item__ufc.selectedAll
                                            var columnModel = model.display
                                            columnModel.title = id_filtableview__ufc.customItem(id_component__column_checkbox, {"checked": checked})
                                            model.display = columnModel
                                            for (var i = 0; i < id_filtableview__ufc.rows; i++) {
                                                var rowData = id_filtableview__ufc.getRow(i)
                                                rowData.checkbox = id_filtableview__ufc.customItem(id_component__checkbox, {"checked": checked})
                                                id_filtableview__ufc.setRow(i, rowData)
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        Component {
                            id: id_component__action
                            Item {
                                RowLayout {
                                    anchors.centerIn: parent
                                    FilIconButton {
                                        Layout.rightMargin: 2
                                        iconSource: FilIcons.OpenFile
                                        iconSize: 16
                                        onClicked: {
                                            id_filtableview__ufc.closeEditor()
                                            id_filedialog__openfile.open()
                                        }
                                    }
                                    FileDialog {
                                        id: id_filedialog__openfile
                                        title: qsTr("Open File")
                                        fileMode: FileDialog.OpenFile
                                        currentFolder: StandardPaths.standardLocations(StandardPaths.PicturesLocation)[0]
                                        onAccepted: {
                                            var text = FilTools.toLocalPath(selectedFile).replace(/\\/g, "/")
                                            var obj = id_filtableview__ufc.getRow(row)
                                            obj.path = text
                                            id_filtableview__ufc.setRow(row, obj)
                                        }
                                    }
                                }
                            }
                        }

                        Component {
                            id: id_component__path
                            Item {
                            }
                        }

                        FilTableView {
                            id: id_filtableview__ufc
                            anchors.fill: parent
                            onRowsChanged: {
                            }
                            startRowIndex: 1
                            columnSource: [
                                {
                                    title: id_filtableview__ufc.customItem(id_component__column_checkbox, {checked: true}),
                                    dataIndex: 'checkbox',
                                    frozen: true,
                                    width: id_row__interval.header[1].width
                                },
                                {
                                    title: qsTr("Path"),
                                    dataIndex: 'path',
                                    frozen: true,
                                    readOnly: true,
                                    width: id_row__interval.header[2].width
                                },
                                {
                                    title: qsTr("Options"),
                                    dataIndex: 'action',
                                    width: id_row__interval.header[3].width,
                                    frozen: true
                                }
                            ]
                        }

                        Component.onCompleted: {
                            // console.log("Component.onCompleted, debug=", AppInfo.debugEnable)
                            if (false/*AppInfo.debugEnable*/) {
                                var dataSource = []
                                var filestr = FilTools.readFile(FilTools.getApplicationDirPath() + "/example/20250101010101001.json")
                                var jsonObject = JSON.parse(filestr)
                                console.log(JSON.stringify(jsonObject))
                                id_filframe__uploadfileconfig.jsonfile = jsonObject
                                var files = jsonObject["files"]
                                if (!files) {
                                    console.warn("files object not exist")
                                    return
                                }
                                for (var i = 0; i < files.length; i++) {
                                    dataSource.push({
                                        checkbox: id_filtableview__ufc.customItem(id_component__checkbox, {checked: files[i]["enable"]}),
                                        path: files[i]["path"],
                                        action: id_filtableview__ufc.customItem(id_component__action, {}),
                                        _key: FilTools.uuid()
                                    })
                                }
                                id_filtableview__ufc.dataSource = dataSource
                            }
                        }
                    }
                }
                function getUploadFilesConfigJson() {
                    var files = []
                    console.log("id_filtableview__ufc.rows:", id_filtableview__ufc.rows)
                    for (var i = 0; i < id_filtableview__ufc.rows; i++) {
                        var enable = id_filtableview__ufc.getRow(i).checkbox.options.checked === true ? true : false;
                        var path   = id_filtableview__ufc.getRow(i).path
                        if (path.length <= 0) {
                            continue
                        }
                        files.push({
                            "enable" : enable,
                            "path"   : path
                        })
                    }
                    if (files.length > 0) {
                        // var obj = {"files": files}
                        // console.log("files:", JSON.stringify(files))
                    }
                    return files
                }
            }
            /**********************************/
            /**********************************/
            /**********************************/
            /**********************************/
            FilFrame {
                id: id_filframe__commit
                Layout.fillWidth: true
                padding: 10
                color: "transparent"
                Layout.preferredHeight: 50
                Layout.rightMargin: control.rightScrollableMargin
                Layout.topMargin: control.frameSpacing
                background: Rectangle {
                    color: "transparent"
                }
                FilText {
                    text: qsTr("Tips: The confirmation button is located in the title bar of the page.")
                }
            }
        }
        Item {
            Layout.preferredWidth: parent.width
            Layout.preferredHeight: control.footerHeight
            Layout.margins: 5
        }
    }

    FilContentDialog {
        id: id_filcontentdialog__back
        title: qsTr("Back")
        message: qsTr("Your changes will not be saved.")
        buttonFlags: FilContentDialogType.NegativeButton | FilContentDialogType.PositiveButton
        onPositiveClicked: {
            parentStackView.popCurrentItem()
        }
    }

    FilContentDialog {
        id: id_filcontentdialog__warning
        property string msg: ""
        title: qsTr("Warning")
        buttonFlags: FilContentDialogType.PositiveButton
        message: qsTr(msg)
        function setMsg(text) {
            msg = text
        }
    }

    ProjectDbHelperCallable {
        id: id_pdhc__read
        onStart: {

        }
        onFinish: {

        }
        onError: (result) => {
            console.warn(result)
        }
        onReadRecordByPid: (ppid, nname, wwdir, ddspath, rrds, uuspath, rrus, ffsw, llstime) => {
            control.pname           = nname
            control.wdir            = wwdir
            control.dspath          = ddspath
            control.dspath_enable   = rrds
            control.uspath          = uuspath
            control.uspath_enable   = rrus
            control.enable_fsw      = ffsw
        }
    }

    function setModifyPid(pid) {
        control.modifyPid = pid
    }

    function loadDataToTableViewByPid(pid) {
        var dataSource = []
        var filestr = ProjectFileWatcher.readFileDataByPid(control.modifyPid)
        if (filestr.length <= 0) {
            console.log("loadDataToTableViewByPid readFile empty")
            return
        }

        var jsonObject = JSON.parse(filestr)
        console.log(JSON.stringify(jsonObject))
        id_filframe__uploadfileconfig.jsonfile = jsonObject
        var files = jsonObject["files"]
        if (!files) {
            id_item__ufc.selectedAll = false
            console.warn("files object not exist")
            return
        }
        for (var i = 0; i < files.length; i++) {
            dataSource.push({
                checkbox: id_filtableview__ufc.customItem(id_component__checkbox, {checked: files[i]["enable"]}),
                path: files[i]["path"],
                action: id_filtableview__ufc.customItem(id_component__action, {}),
                _key: FilTools.uuid()
            })
            if (files[i]["enable"] === false) {
                id_item__ufc.selectedAll = false
            }
        }
        id_filtableview__ufc.dataSource = dataSource
    }

    function loadDataFromDatabaseByPid(pid) {
        console.log("loadDataFromDatabaseByPid")
        ProjectDbHelper.readRecordByPid(pid, id_pdhc__read)
    }

    function modifyProject() {
        if (control.pname.length <= 0) {
            showInfo(qsTr("Invalid Project Name"))
            return ;
        }

        var dateTimeStr = FilTools.getCurrentDateTimeToString("yyyyMMddHHmmsszzz")
        var dateTimeStrModify = FilTools.getCurrentDateTimeToString("yyyy-MM-dd HH:mm:ss.zzz")
        var files = id_filframe__uploadfileconfig.getUploadFilesConfigJson()
        console.log("Start Modify Project pid:", control.modifyPid)
        console.log("===================================================")
        console.log("|| name          : ", control.pname)
        console.log("|| wdir          : ", control.wdir)
        console.log("|| dspath        : ", control.dspath)
        console.log("|| dspath_enable : ", control.dspath_enable)
        console.log("|| uspath        : ", control.uspath)
        console.log("|| uspath_enable : ", control.uspath_enable)
        console.log("|| enable_fsw    : ", control.enable_fsw)
        console.log("|| files         : ", JSON.stringify(files))
        console.log("===================================================")

        if (ProjectDbHelper.modify(
            control.modifyPid,
            control.pname,
            control.wdir,
            control.dspath,
            control.dspath_enable,
            control.uspath,
            control.uspath_enable,
            control.enable_fsw,
            dateTimeStrModify)) {

            var uploadFileConfigStr = ProjectFileWatcher.readFileDataByPid(control.modifyPid)
            if (uploadFileConfigStr.length > 0) {
                var uploadFileConfig = JSON.parse(uploadFileConfigStr)
                if (files.length > 0) {
                    uploadFileConfig["files"] = files
                    console.log("has files, to update upload file config to json file.")
                    if (ProjectFileWatcher.writeFileDataByPid(control.modifyPid, JSON.stringify(uploadFileConfig, null, 4))) {
                    }
                }
            } else {
                // new json file
                var os = FilTools.isWin() ? "WIN" : FilTools.isLinux() ? "LINUX" : FilTools.isMacos() ? "MAC" : "UNKNOWN"
                var uploadFileConfigg = {"pid": control.modifyPid, "os": os, "files": files}
                if (files.length > 0) {
                    console.log("has files, to write upload file config to json file.")
                    if (ProjectFileWatcher.writeFileDataByPid(control.modifyPid, JSON.stringify(uploadFileConfigg, null, 4))) {
                    }
                }
            }

            showSuccess("Modify Project Success.", 2)
            // 修改成功后退栈
            parentStackView.popCurrentItem()
        } else {
            showError("Modify Project Failure.")
        }
    }

    StackView.onActivating: {
        loadDataFromDatabaseByPid(control.modifyPid)
        loadDataToTableViewByPid(control.modifyPid)
    }
}
